# *-# -*- coding: utf-8 -*-

import os
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
#import textwrap
import wrap
import twitter
import sqlite3
from threading import Timer
import datetime


TWITTER_SETTINGS = {
        'Test': {
                'user':'test',
                'password':'1234',
            },
    }

PRINTER_NAME = '"EPSON TM-L90 Receipt"'
DB_FILE_NAME = 'tweets_print.db'

GSPRINT_COMMAND = 'gsprint.exe'

def initDB():
    printLOG('DB', 'Initializing DB ...')
    if not (os.path.isfile(DB_FILE_NAME)):
        db=sqlite3.connect(DB_FILE_NAME)
        db.execute('create table tweet_id(id integer PRIMARY KEY AUTOINCREMENT, user, tweet_id)')
        
        for key, twitter_account in TWITTER_SETTINGS.items():
            twitter_api = twitter.Api(twitter_account['user'], twitter_account['password'])
            
            #Replies
            get_replies = twitter_api.GetReplies()
            for reply in get_replies:
                db.execute('insert into tweet_id(user, tweet_id) values (?, ?)', [twitter_account['user'], (str(reply.GetId()))])
            db.commit()
            #db.close()
            printLOG('DB', key + ': Add ' + str(len(get_replies)) + ' replies.')
            
            #Favorites
            get_favorites = twitter_api.GetFavorites()
            for favorite in get_favorites:
                db.execute('insert into tweet_id(user, tweet_id) values (?, ?)', [twitter_account['user'], (str(favorite.GetId()))])
            db.commit()
            printLOG('DB', key + ': Add ' + str(len(get_replies)) + ' favorites.')
        
        db.close()

def checkTweets():
    printLOG('Tweets', 'Checking Tweets ...')
    db=sqlite3.connect(DB_FILE_NAME)
    cur = db.cursor()
    
    for key, twitter_account in TWITTER_SETTINGS.items():
        printLOG('Tweets', key + ': Checking...')
        twitter_api = twitter.Api(twitter_account['user'], twitter_account['password'])
        
        #Replies
        get_replies = twitter_api.GetReplies()
        for reply in get_replies:
            cur.execute("select tweet_id from tweet_id where user = ? and tweet_id = ?", [twitter_account['user'], (str(reply.GetId()))])
            if len(cur.fetchall()) == 0:
                printLOG('Tweets', key + ': Tweets Found !! (Reply)')
                createPDF(twitter_account['user'], reply)
                printPDF(twitter_account['user'], str(reply.GetId()))
                db.execute('insert into tweet_id(user, tweet_id) values (?, ?)', [twitter_account['user'], (str(reply.GetId()))])
                printLOG('DB', key + ': Insert ID ' + (str(reply.GetId())))
                
        #Favorites
        get_favorites = twitter_api.GetFavorites()
        for favorite in get_favorites:
            cur.execute("select tweet_id from tweet_id where user = ? and tweet_id = ?", [twitter_account['user'], (str(favorite.GetId()))])
            if len(cur.fetchall()) == 0:
                printLOG('Tweets', key + ': Tweets Found !! (Favorite)')
                createPDF(twitter_account['user'], favorite)
                printPDF(twitter_account['user'], str(favorite.GetId()))
                db.execute('insert into tweet_id(user, tweet_id) values (?, ?)', [twitter_account['user'], (str(favorite.GetId()))])
                printLOG('DB', key + ': Insert ID ' + (str(favorite.GetId())))
            
    db.commit()
    cur.close()
    db.close()
    
def createPDF(user, tweet):
    printLOG('PDF', 'Creating PDF ...')
    os.chdir('pdf')
    
    if not (os.path.isdir(user)):
        os.mkdir(user)
        
    os.chdir(user)
    
    tweet_id = str(tweet.GetId())
    filename = tweet_id + '.pdf'
    
    printLOG('PDF', 'Creating ' + filename)
    
    c = canvas.Canvas(filename, pagesize=(220,300))
    msgothic = TTFont('MS Gothic','msgothic.ttc',subfontIndex=0,asciiReadable=0)
    pdfmetrics.registerFont(msgothic)
    
    try:
        image = tweet.GetUser().GetProfileImageUrl().encode('UTF-8')
        c.drawImage('..' + os.sep + 'twitter_logo_header.jpg', 35, 260)
        c.drawInlineImage(image, 10, 200)
    except:
        pass
        
    name = tweet.GetUser().GetScreenName().encode('utf-8')
    c.setFont('MS Gothic', 15)
    t = c.beginText(65, 205)
    t.textLines(name)
    c.drawText(t)

    c.setFont('MS Gothic', 10)
    
    utc_offset = tweet.GetUser().GetUtcOffset()
    date = datetime.datetime.strptime(tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y")
    
    if utc_offset:
        td = datetime.timedelta(seconds=utc_offset)
        post_date = date+td
    else:
        post_date = date
        
    t = c.beginText(10, 185)
    t.textLines(post_date.strftime("%Y-%m-%d %H:%M:%S"))
    c.drawText(t)
    
    text = tweet.GetText().encode('utf-8')
    t = c.beginText(10, 170)
    #result = textwrap.fill(text,  width=20)
    wrap_text = wrap.wrap(text, 40)
    t.textLines(wrap_text.encode('utf-8'))
    c.drawText(t)

    c.showPage()
    c.save()
    
    os.chdir('..' + os.sep + '..')
    
def printPDF(user, tweet_id):
    printLOG('PRINT', 'Printing PDF ...')
    os.chdir('pdf')
    os.chdir(user)
    filename = tweet_id + '.pdf'
    
    printLOG('PRINT', 'Printing ' + filename)
    
    if (os.path.isfile(filename)):
        os.system(GSPRINT_COMMAND + ' -printer ' + PRINTER_NAME + ' ' + filename)
        
    os.chdir('..' + os.sep + '..')
    
def printLOG(section, log):
    date = datetime.datetime.today()
    print '[' + date.strftime('%Y-%m-%d %H:%M:%S') + ' - ' + section + '] ' + log

if __name__ == "__main__":
    printLOG('SYSTEM', 'Starting TweetsPrint ...')
    
    initDB()
    
    checkTweets()
    
    sec = 180.0
    
    printLOG('SYSTEM', 'Timer Setting ... (' + str(sec) + ' sec)')
    
    while True:
        t = Timer(sec, checkTweets)
        t.run()
